package org.qing.cloud.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * 路由限流配置
 * 
 * @author qing
 *
 */
@Slf4j
@Configuration
public class RateLimiterConfiguration {
	
	/**
	 * IP 限流
	 * 
	 * @param
	 * @return
	 */
	@Primary
	@Bean(value = "remoteAddrKeySolver")
	public KeyResolver remoteAddrKeySolver() {
		return (exchange) -> {
			String remoteAddress = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
			log.info("rateLimiter-remote-address=[{}]", remoteAddress);
			return Mono.just(remoteAddress);
		};
	}

	/**
	 * 用户限流
	 * 
	 * @param
	 * @return
	 */
	@Bean(value = "userKeySolver")
	public KeyResolver userKeySolver() {
		return (exchange) -> {
			String userId = exchange.getRequest().getHeaders().getFirst("USER_ID");
			log.info("rateLimiter-user-id=[{}]", userId);
			return Mono.just(userId);
		};
	}

}
